# -*- coding: utf-8 -*-
"""
 GFM is a web app for adding the most hilarious quotes heard at the office,
 association, etc...

 GFM works with Python 2.5, using Juno light web framework and Apache2 as
 webserver.

 ----------------------------------------------------------------------------------
 
 LICENSE:
 
 This file is part of GFM.
 
 GFM is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.
 
 bbPress is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with bbPress; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
 ----------------------------------------------------------------------------------
 
 Python 2.5
 
 ----------------------------------------------------------------------------------
 
 @copyright 2008 José Carlos Cuevas
 @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License v3
 @link      http://frasesmiticas.googlecode.com GFM
 @author    José Carlos Cuevas
"""

import time
import sys
import PyRSS2Gen as rss_gen
import re
import simplejson

from postmarkup import render_bbcode
from juno import *

sys.stdout = sys.stderr

# Juno init

init({'db_type': 'postgres',
      'db_location': 'myth:k05h@192.168.15.44/mythical',
      'dev_port': 8080})

# Model definition

Phrase = model('Phrase', name = 'unicodetext',
                         phrase = 'unicodetext',
                         date_ep = 'integer',
                         date = 'unicodetext')

Comment = model('Comment', content = 'unicodetext',
                          date_ep = 'integer',
                          date = 'unicodetext',
                          ph_id = 'integer')


@get('/')
def index(web):
    """
    Vista de la página principal
    """
    try:
    
        list_phrases = Phrase.find().order_by(Phrase.date_ep.desc())
        num_elems = len(Phrase.find().all())
        num_pages = int(num_elems / 10)

        if (num_elems - (num_pages * 10) > 0): 
            
            num_pages += 1

        num_comments_dict = {}

        for phrase in list_phrases[:10]:

            id_val = phrase.id
            num_comments_dict[id_val] = len(Comment.find().filter(Comment.ph_id == id_val).all())

    except Exception:
        
        return "Error accediendo a la BBDD"

    if list_phrases is None:

        list_phrases = []

        num_pages = None

    if 2 > num_pages:

        trail = num_pages

    else:

        trail = 2

    not_last = (num_pages != 1)

    view_title = u"Las frases míticas de CITIC" 
    
    template('template.html', { 'phrases' : list_phrases[:10],
                                'title' : view_title,
                                'pages' : num_pages,
                                'trail' : trail,
                                'not_last': not_last,
                                'actual': 1,
                                'commentdict': num_comments_dict })


@get('/rss/')
def rss_send(web):
    """
    Devuelve un XML con las 10 ultimas frases
    """
    try:
    
        list_phrases = Phrase.find().order_by(Phrase.date_ep.desc())
        
    except Exception:
        
        return "Error accediendo a la BBDD"

    if list_phrases is None:

        list_phrases = []

        num_pages = None

    list_items = []

    for phrase in list_phrases[:10]:

        rss_item = rss_gen.RSSItem(title = phrase.phrase,
                                   description = "#" + str(phrase.id),
                                   pubDate = phrase.date,
                                   link = "http://192.168.15.44/miticas/phrase/" + str(phrase.id))

        list_items.append(rss_item)

    rss_result = rss_gen.RSS2(title = u"Las frases miticas de CITIC",
                              link = "http://192.168.15.44/miticas",
                              description = u"Las frases más divertidas dichas en CITIC",
                              lastBuildDate = time.asctime(),
                              items = list_items)

    return rss_result.to_xml(encoding = "utf-8")


@get('/page/:num_page')
def all_phrases(web, num_page):
    """
    Paginación...
    """
    num_page = int(num_page)
    try:
    
        list_phrases = Phrase.find().order_by(Phrase.date_ep.desc())
        num_elems = len(Phrase.find().all())
        num_pages = int(num_elems / 10)

        if (num_elems - (num_pages * 10) > 0): 
            
            num_pages += 1

    except Exception:
        
        return "Error accediendo a la BBDD"

    if list_phrases is None:

        list_phrases = []

        num_pages = None

    view_title = u"Las frases míticas de CITIC"

    point_a = (num_page - 1) * 10
    point_b = point_a + 10

    num_comments_dict = {}

    for phrase in list_phrases[point_a:point_b]:

        num_comments_dict[phrase.id] = len(Comment.find().filter(Comment.ph_id == phrase.id).all())

    if (num_page + 2) > num_pages:

        trail = num_pages

    else:

        trail = num_page + 2

    not_last = not (num_page == num_pages)

    template('template.html', { 'phrases' : list_phrases[point_a:point_b],
                                'title' : view_title,
                                'pages' : num_pages,
                                'trail' : trail,
                                'not_last' : not_last,
                                'actual': num_page,
                                'commentdict': num_comments_dict })

@get('/phrase/:num_id/')
def get_phrase(web, num_id):
    """
    This method allows us to see the desired quote and related comments
    """
    fetch_id = int(num_id)
    phrase = Phrase.find().filter(Phrase.id == fetch_id).first()
    comments = find(Comment).filter(Comment.ph_id == fetch_id).order_by(Comment.date_ep.asc())

    template('comment.html', { 'title': u'Las frases míticas de CITIC',
                               'phrase': phrase,
                               'comments': comments })


@get('/check_new/:last_id')
def check_new(web, last_id):
    """
    This method returns a json'd dict to the AJAX method for refreshing
    """
    list_phrases = Phrase.find().order_by(Phrase.date_ep.desc()) 
        
    last_phrase = list_phrases[0]

    if last_phrase.id != int(last_id):

        response = {}
        id_val = last_phrase.id
        num_comments = len(Comment.find().filter(Comment.ph_id == int(id_val)).all())
        response["id"] = last_phrase.id
        response["phrase"] = last_phrase.phrase
        response["date"] = last_phrase.date
        response["comments"] = num_comments

        return simplejson.dumps(response)

    else:

        return simplejson.dumps(False)


@post('/phrase/:num_id/comment/')
def post_comment(web, num_id):
    num_id = int(num_id)

    comment_text = render_bbcode(web.input('comment'), encoding="utf-8")
    
    comment = Comment(ph_id = num_id,
                      content = comment_text,
                      date_ep = time.time(),
                      date = time.asctime())

    comment.add()
    comment.save()

    redirect('/miticas/phrase/' + str(num_id), 302)

@post('/new_phrase/')
def post_new(web):
    """
    Colgar una nueva frase
    """
    new_phrase = web.input('phrase')
    new_date_ep = time.time()
    new_date = time.asctime()

    new_phrase = Phrase(name = "placeholder",
                        phrase = render_bbcode(new_phrase, encoding="utf-8"),
                        date_ep = new_date_ep,
                        date = new_date)

    new_phrase.add()
    new_phrase.save()

    redirect('/miticas', 302)


config('mode', 'wsgi')
application = run()
